package com.example.module.system.api.mail;

import cn.hutool.core.util.ObjectUtil;
import com.example.framework.common.constant.MessageSendType;
import com.example.framework.common.exception.ServiceException;
import com.example.module.system.api.mail.dto.EmailSendParam;
import com.example.module.system.enums.ErrorCodeConstants;
import com.example.module.system.service.sendrecord.MessageSendRecordService;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Objects;

@Slf4j
@Service
public class MailSendApiImpl implements MailSendApi {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private MessageSendRecordService messageSendRecordService;

    @Override
    @Async("ttlThreadPoolExecutor")
    public void sendSingleMsg(EmailSendParam emailSendParam) {
        log.info("准备发送邮件，emailSendParam={}", emailSendParam);
        try {
            // 创建一个邮件消息
            MimeMessage message = javaMailSender.createMimeMessage();

            // 创建 MimeMessageHelper
            File file = emailSendParam.getFile();
            MimeMessageHelper helper = new MimeMessageHelper(message, false);

            // 发件人邮箱和名称
            helper.setFrom(from, "Lexar");
            // 收件人邮箱
            helper.setTo(emailSendParam.getReceiver());
            // 邮件标题
            helper.setSubject(emailSendParam.getTitle());
            // 邮件正文，第二个参数表示是否是HTML正文
            helper.setText(emailSendParam.getMsg(), emailSendParam.getHtml());
            // 抄送人
            String[] cc = emailSendParam.getCc();
            if (ObjectUtil.isNotEmpty(cc)) {
                helper.setCc(cc);
            }
            // 附件
            if (Objects.nonNull(file)) {
                helper.addAttachment(file.getName(), file);
            }

            // 发送
            javaMailSender.send(message);

            messageSendRecordService.saveResult(MessageSendType.EMAIL, "success", emailSendParam.getReceiver(), emailSendParam.getMsg());
        } catch (Exception e) {
            String errMsg = e.getMessage();
            log.error("发送邮件出现异常，e={}", errMsg);
            messageSendRecordService.saveResult(MessageSendType.EMAIL, errMsg, emailSendParam.getReceiver(), emailSendParam.getMsg());
            throw ServiceException.of(ErrorCodeConstants.SEND_MAIL_ERROR, errMsg);
        }
    }
}
